import React, { useState } from 'react'
import { connect } from 'react-redux'
import { toggleAudio, toggleVideo, changePeerStream } from '@/utils/webRtc'
import { copyData } from '@/utils/index'

import './index.scss'

const Control = ({
  roomInfo,
  openAudio,
  openCamera,
  showUsers,
  setShowUsers
}) => {

  /**
   * 点击麦克风
   */
  const onclickMicrophone = (val) => {
    toggleAudio(val)
  }
  /**
   * 点击摄像头
   */
  const onclickCamera = (val) => {
    toggleVideo(val)
  }

  const [screenStream, setScreenStream] = useState(null)
  /**
   * 点击共享屏幕
   */
  const onclickShareScreen = async() => {
    /* 没有进行分享，或者已经中断分享时进入分享 */
    if (!screenStream || !screenStream.active) {
      try {
        const stream = await navigator.mediaDevices.getDisplayMedia({
          audio: true,
          video: true
        })

        setScreenStream(stream)
        changePeerStream(stream)
      } catch (err) {
        console.log('打开分享失败', err)
      }
    } else {
      setScreenStream(null)
      screenStream.getTracks().forEach(track => track.stop())
      changePeerStream()
    }
  }
  /**
   * 点击分享
   */
  const onclickShare = () => {
    const host = location.origin

    copyData(`${ host }/#/join-room/Audience?roomId=${ roomInfo.id }`, true)
  }

  return (
    <div className="video-room-control">
      <div
        className="video-room-control-item"
        onClick={() => onclickMicrophone(!openAudio)}
      >
        <i
          className={['iconfont', openAudio ? ' icon-maikefeng' : 'icon-maikefeng1'].join(' ')}
          style={{
            'color': openAudio ? '#333' : 'red'
          }}
        />
        <p className="label">麦克风</p>
      </div>
      <div
        className="video-room-control-item"
        onClick={() => onclickCamera(!openCamera)}
      >
        <i
          className={['iconfont', openCamera ? ' icon-shexiangtou_shiti' : 'icon-shexiangtou_guanbi'].join(' ')}
          style={{
            'color': openCamera ? '#333' : 'red'
          }}
        />
        <p className="label">摄像头</p>
      </div>
      <div
        className="video-room-control-item"
        onClick={onclickShareScreen}>
        <i className="iconfont icon-pingmugongxiang" />
        <p className="label">共享</p>
      </div>
      <div
        className="video-room-control-item"
        onClick={() => setShowUsers(!showUsers)}
        style={{
          'color': showUsers ? 'red' : '#333'
        }}
      >
        <i className="iconfont icon-yonghufill" />
        <p className="label">成员</p>
      </div>
      <div
        className="video-room-control-item"
        onClick={onclickShare} >
        <i className="iconfont icon-fenxiang" />
        <p className="label">分享</p>
      </div>
    </div>
  )
}

const mapStateToProps = (state) => ({ ...state })

export default connect(mapStateToProps)(Control)
